package com.zhupanlin.zhyl.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhupanlin.zhyl.cmn.client.DictFeignClient;
import com.zhupanlin.zhyl.common.exception.Zhylxception;
import com.zhupanlin.zhyl.common.result.ResultCodeEnum;
import com.zhupanlin.zhyl.common.util.MD5;
import com.zhupanlin.zhyl.hosp.repository.HospitalRepository;
import com.zhupanlin.zhyl.hosp.service.HospitalService;
import com.zhupanlin.zhyl.hosp.service.HospitalSetService;
import com.zhupanlin.zhyl.model.hosp.Hospital;
import com.zhupanlin.zhyl.model.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/11/23 17:52
 */
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private HospitalSetService hospitalSetService;

    @Autowired
    private DictFeignClient dictFeignClient;


    /**
     * 上传医院接口
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 判断签名是否符合
        checkSign(paramMap);

        // 把参数 map 集合转换对象 Hospital
        String jsonString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        // 传输过程中 "+" 转换为了 " "，需要转换回来
        String logoData = hospital.getLogoData();
        logoData = logoData.replaceAll(" ", "+");
        hospital.setLogoData(logoData);

        // 判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExists = hospitalRepository.getHospitalByHoscode(hoscode);


        if (hospitalExists != null) {
            // 如果存在，就修改
            hospital.setStatus(hospitalExists.getStatus());
            hospital.setCreateTime(hospitalExists.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
        } else {
            // 如果不存在，进行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
        }
        hospitalRepository.save(hospital);
    }

    /**
     * 根据医院编号进行查询
     *
     * @param paramMap
     * @return
     */
    @Override
    public Hospital getHospitalByHoscoe(Map<String, Object> paramMap) {
        checkSign(paramMap);
        String hoscode = (String) paramMap.get("hoscode");
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    @Override
    public void checkSign(Map<String, Object> paramMap) {
        // 1.获取医院系统传递过来的签名，签名经过 MD5 的加密
        String hospSign = (String) paramMap.get("sign");
        String hoscode = (String) paramMap.get("hoscode");

        // 2.从数据库中查询签名
        String signKey = hospitalSetService.getSignKey(hoscode);

        // 3.把签名进行 MD5 加密
        String signKeyMd5 = MD5.encrypt(signKey);

        // 4.判断签名是否一致
        if (!hospSign.equals(signKeyMd5)) {
            throw new Zhylxception(ResultCodeEnum.SIGN_ERROR);
        }
    }

    /**
     * 医院列表(分页条件查询)
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> seleceHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 创建 Pageable 对象
        Pageable pageable = PageRequest.of(page - 1, limit);

        // 创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pageModel = hospitalRepository.findAll(example, pageable);

        List<Hospital> hospitals = pageModel.getContent();
        hospitals.stream().forEach(item -> {
            setHospitalLevel(item);
        });

        return pageModel;
    }

    /**
     * 更新医院上线状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    /**
     * 医院详情信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getHospById(String id) {
        Map<String, Object> map = new HashMap<>();
        Hospital hospital = hospitalRepository.findById(id).get();
        Hospital hospitalLevel = setHospitalLevel(hospital);
        // 医院基本信息（包含医院等级）
        map.put("hospital", hospitalLevel);
        // 单独返回医院预约信息
        map.put("bookingRule", hospitalLevel.getBookingRule());
        hospitalLevel.setBookingRule(null);

        return map;
    }

    /** 获取医院名称
     * @param hoscode
     * @return
     */
    @Override
    public String getHospNameByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital == null) {
            return null;
        }
        return hospital.getHosname();
    }

    /**
     * 根据医院名称查询
     *
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> list = hospitalRepository.findHospitalByHosnameLike(hosname);
        return list;
    }

    /**
     * 根据医院编号获取医院预约挂号详情
     *
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 进行医院等级封装
     * @param hospital
     */
    private Hospital setHospitalLevel(Hospital hospital) {
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        // 查询 省 市 区
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("fullAddress", provinceString + cityString + districtString);
        hospital.getParam().put("hostypeString", hostypeString);
        return hospital;
    }
}
